
var order_report_selected_id;

var direction;
var column;
function sortOrderReport(id) {
    if (id == "report_id")
        return;
    column = $('#'+id).attr('value');
    var imgid = order_report_selected_id + '_img';
    $('#'+order_report_selected_id).html($('#'+order_report_selected_id).html());    
    if (id == order_report_selected_id) {
        if ($('#'+imgid).attr('src') == '../images/down.png') {
            $('#'+imgid).prop('src', '../images/up.png');
            direction = 'up';
        } else {
            $('#'+imgid).prop('src', '../images/down.png');
            direction = 'down';
        }
    } else {
        $('#'+imgid).prop('src', '');
        imgid = id + '_img';
        $('#'+imgid).prop('src', '../images/up.png');
        direction = 'up';
    }
    $('#'+order_report_selected_id).html($('#'+order_report_selected_id).html());
    order_report_selected_id = id;
    generateOrderReport();
}

function generateOrderReport() {
    var dataString = 'action=generate' + 
            '&dateFrom=' + $('#fromdatepicker').val() + 
            '&dateTo=' + $('#todatepicker').val() + 
            '&warehouse=' + $("#warehouse_selection :selected").attr('id') + 
            '&customer=' + $('#customer_selection :selected').attr('id') + 
            '&state=' + $('#state_selection :selected').attr('id') + 
            '&start=' + $('#start_record').val() + 
            '&quantity=' + $('#records_quantity').val() +
            '&column=' + column + 
            '&direction=' + direction;
    if (!checkValidate($('#fromdatepicker'), $('#fromdatepicker'), "^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20){1}[0-9]{2})*$")) {
        return;
    }
    if (!checkValidate($('#todatepicker'), $('#todatepicker'), "^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20){1}[0-9]{2})*$")) {
        return;
    }
    sendData(dataString, "OrderReportOperation", function(data){
        var htmlStr = $('#report-table').html();
        htmlStr = htmlStr.substring(0, htmlStr.indexOf('</tbody>'));
        if (htmlStr.indexOf('</tbody>') == -1) {
            htmlStr = htmlStr.substring(0, htmlStr.indexOf('</tr>'));
            htmlStr += '</tr>';
        }
        htmlStr = htmlStr.replace('</tbody>', '');
        var num = $('#start_record').val();
        for (var i = 0; i < data.length; i++) {
            htmlStr += '<tr>';
            htmlStr += '<td>'+ num + '</td>';
            htmlStr += '<td><a href="admin.jsp?content=revieworder&id=' + data[i].id + '">'+ data[i].id +'</a></td>';
            htmlStr += '<td>'+ data[i].state +'</td>';
            htmlStr += '<td>'+ data[i].login +'</td>';
            htmlStr += '<td>'+ data[i].create +'</td>';
            htmlStr += '<td>'+ data[i].warehouse +'</td>';
            htmlStr += '<td>'+ data[i].total +'</td>';
            htmlStr += '</tr>';
            num++;
        }
        $('#report-table').html(htmlStr);
    });
}

function exportOrderReport() {
    var dataString = 'action=export' + 
            '&dateFrom=' + $('#fromdatepicker').val() + 
            '&dateTo=' + $('#todatepicker').val() + 
            '&warehouse=' + $("#warehouse_selection :selected").attr('id') + 
            '&customer=' + $('#customer_selection :selected').attr('id') + 
            '&state=' + $('#state_selection :selected').attr('id') + 
            '&start=' + $('#start_record').val() + 
            '&quantity=' + $('#records_quantity').val() + 
            '&column=' + column + 
            '&direction=' + direction;
    if (!checkValidate($('#fromdatepicker'), $('#fromdatepicker'), "^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20){1}[0-9]{2})*$")) {
        return;
    }
    if (!checkValidate($('#todatepicker'), $('#todatepicker'), "^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20){1}[0-9]{2})*$")) {
        return;
    }
    sendData(dataString, "OrderReportOperation", function(data){
        window.location.href = data.file;
    });
}

function is_positive_int(event, value) {
    var old_value = value;
    var c = String.fromCharCode(event.keyCode);
    var new_value = old_value + c;
    return ((validate(new_value, '^[1-9]+[0-9]*$')) || (event.keyCode==8)
                    || (event.keyCode == 37)
                    || (event.keyCode == 39)
                    || (event.keyCode == 46));
}


function generatePopularityReport() {
    var dataString = 'action=generate' + 
            '&warehouse=' + $("#warehouse_selection :selected").attr('id') + 
            '&start=' + $('#start_record').val() + 
            '&quantity=' + $('#records_quantity').val();
    sendData(dataString, "PopularityReportOperation", function(data) {
        var htmlStr = '<tr>' + 
                '<td>#</td>' +
                '<td>Warehouse</td>' +
                '<td>Commodity Name</td>' +
                '<td>Commodity Popularity</td>' +
            '</tr>';
        var num = $('#start_record').val();
        for (var i = 0; i < data.length; i++) {
            htmlStr += '<tr>';
            htmlStr += '<td>'+ num + '</td>';
            htmlStr += '<td>'+ data[i].warehouse +'</td>';
            htmlStr += '<td>'+ data[i].commodity +'</td>';
            htmlStr += '<td>'+ data[i].quantity +'</td>';
            htmlStr += '</tr>';
            num++;
        }
        $('#report-table').html(htmlStr);
    });
}

function exportPopularityReport() {
    var dataString = 'action=export' + 
            '&warehouse=' + $("#warehouse_selection :selected").attr('id') + 
            '&start=' + $('#start_record').val() + 
            '&quantity=' + $('#records_quantity').val();
    sendData(dataString, "PopularityReportOperation", function(data) {
        window.location.href = data.file;
    });
}

function fileSelected(input) {
     if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#picture_commodity').attr('src',e.target.result)
            var str = '' + e.target.result;
            str = str.substr(str.indexOf('/') + 1, str.indexOf(';') - str.indexOf('/') - 1)
            $('#file_name').prop('value', str);
        };
        reader.readAsDataURL(input.files[0]);
     }
}

function validate(value, pattern) {
    var reg = new RegExp(pattern);
    return reg.test(value);
}

function showDialog() {
    var field = "";
    if ($('#name_commodity').val() == "") {
        field += "input name, "
    }
    if (!validate($('#price_commodity').val(), "^[1-9]+[0-9]*([\.\,][0-9]+)?$")) {
        field += "check price format, ";
    }
    if ($('#desc_commodity').val() == "") {
        field += "input description, ";
    }
    if (document.getElementById('selectFile').files[0] == null && isNaN($('#id_commodity').attr('value'))) {
        field += "add picture."
    }
    if (field.substr(field.length - 1, 1) != ".") {
        field = field.substr(0, field.length - 2);
        field += ".";
    }
    var dialog = '<div id="message"><div id="dark-font"></div>'
                   + '<div id="dialog-outer">' 
                   + '<div id="dialog">' 
                   + '<h1>Illegal values!</h1>' 
                   + 'Please, ' + field
                   + '<div style="text-align: center; margin-top: 30px;">' 
                   + '<input type="button" value="Ok" id="ok_btn"/>'
                   + '</div></div></div></div>';
    $("#content").after(dialog);
    $("#ok_btn").click(function() {
        $("#message").remove();
    });
}

function price_commodity_changed(event) {
    var old_value = $('#price_commodity').val();
    var c = String.fromCharCode(event.keyCode);
    var new_value = old_value + c;
    return ((validate(new_value, '^[0-9]+[0-9]*\.?[0-9]*$')) || (event.keyCode==8)
                    || (event.keyCode == 37)
                    || (event.keyCode == 39)
                    || (event.keyCode == 46));
}

$(document).ready(function() {
    
    $('#save_created').unbind('click').click(function() {
        if ($('#name_commodity').val() == ""
                || !validate($('#price_commodity').val(), "^[1-9]+[0-9]*([\.\,][0-9]+)?$")
                || $('#desc_commodity').val() == ""
                || ! document.getElementById('selectFile').files[0]) {
            showDialog();
            return;
        }
        var dataString = 'action=create' +
                '&name=' + $('#name_commodity').val() + 
                '&categoryId=' + $("#categories_selection :selected").attr('value') + 
                '&price=' + $('#price_commodity').val() + 
                '&description=' + $('#desc_commodity').val();
        sendData(dataString, "CommodityOperation", function(data) {
            $('#commodity_id').prop('value', data.idCommodity);
            $('#form-image').submit();
        });
    });
    
    $('#save_edited').unbind('click').click(function() {
        if ($('#name_commodity').val() == ""
                || !validate($('#price_commodity').val(), "^[1-9]+[0-9]*([\.\,][0-9]+)?$")
                || $('#desc_commodity').val() == "") {
            showDialog();
            return;
        }
        var dataString = 'action=edit' + '&id=' + $('#id_commodity').attr('value') + 
                '&name=' + $('#name_commodity').val() + 
                '&price=' + $('#price_commodity').val() + 
                '&categoryId=' + $("#id_commodity").attr('catid') + 
                '&description=' + $('#desc_commodity').val();        
        sendData(dataString, "CommodityOperation", function(data) {
            $('#commodity_id').prop('value', data.idCommodity);
            $('#form-image').submit();
        });        
    });
    
    $("#all_commodities").unbind('click').click(function() {
        var commodities = $("[name='commodities']");
        var checked = $('#all_commodities').is(':checked');
        for (var i = 0; i < commodities.length; i++) {
            $(commodities[i]).prop('checked', checked);
        }
    });
    
    $("#ship_btn").unbind('click').click(function() {
        var dataString = 'id=' + $("#id_order").attr('value') + 
                    '&action=ship' +
                    '&comment=' + $('#comment').val();
        sendData(dataString, "OrderOperation", orderSuccess);
    });
    
    function orderSuccess(data) {
        window.location.replace('admin.jsp?content=order');
    }    
    
    $("#cancel_btn").unbind('click').click(function() {
        var dataString = 'id=' + $("#id_order").attr('value') +
                    '&action=cancel' + 
                    '&comment=' + $('#comment').val();
        sendData(dataString, "OrderOperation", orderSuccess);
    });

    $("#delete_commodity_btn").unbind('click').click(function() {
        var commodities = $("[name='commodities']");
        
        var ids = 'id=';
        for (var i = 0; i < commodities.length; i++) {
            if ($(commodities[i]).is(':checked')) {
                ids += ($(commodities[i]).attr('id') + ';');
            }
        }
        ids = ids.substr(0, ids.length - 1);
        var dataString = ids + '&action=delete';
        sendData(dataString, "CommodityOperation", function(){
            window.location.replace('admin.jsp?content=product');
        });
    });
        
});

function sendData(dataString, dest, onSuccess) {
    $.ajax({
        type: "POST",
        url: dest,
        data: dataString,
        success:  function(response_data) {
            onSuccess(response_data);
        },
        error: function() {
            console.log('error');
        }
    });
};